package com.lingyun.admin.controller.system.role;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.lingyun.common.annotation.Log;
import com.lingyun.common.corebase.GeneralEntity;
import com.lingyun.common.exception.role.RoleHaveUserCanNotDelException;
import com.lingyun.common.pojo.LyRole;
import com.lingyun.common.pojo.LyUserRole;
import com.lingyun.common.utils.AjaxResult;
import com.lingyun.common.utils.file.FileDownloadUtils;
import com.lingyun.common.vo.role.AllocationUserCondition;
import com.lingyun.common.vo.role.UpdateRoleStatus;
import com.lingyun.system.service.LyRoleService;
import io.swagger.annotations.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 角色管理
 *
 * @author 没事别学JAVA
 */
@RestController
@RequestMapping("/system/role")
@Api(value = "角色管理", tags = "角色管理")
public class RoleController {


    @Resource
    LyRoleService lyRoleService;


    /**
     * 查询角色列表（下拉框）
     *
     * @return 角色列表
     */
    @ApiOperation(value = "查询角色列表（下拉框）")
    @GetMapping("/selectOption")
    public AjaxResult selectOption() {
        return AjaxResult.success(lyRoleService.selectOption());
    }


    /**
     * 根据条件分页查询角色列表
     *
     * @param generalEntity 角色筛选条件
     * @return 角色分页数据
     */
    @ApiOperation(value = "根据条件分页查询角色列表")
    @Log(title = "角色模块", businessType = "0", description = "根据条件分页查询角色列表")
    @PreAuthorize("hasRole('system:role:rolelist')")
    @GetMapping("/roleList")
    public AjaxResult roleList(GeneralEntity generalEntity) {
        return AjaxResult.success(lyRoleService.roleList(generalEntity));
    }


    /**
     * 添加角色
     *
     * @param lyRole 角色信息
     * @return 结果
     */
    @ApiOperation(value = "添加角色")
    @Log(title = "角色模块", businessType = "1", description = "添加角色")
    @PreAuthorize("hasRole('system:role:addrole')")
    @PostMapping("/addRole")
    public AjaxResult addRole(@RequestBody LyRole lyRole) {
        if (lyRoleService.addRole(lyRole) > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("角色添加失败");
    }


    /**
     * 根据角色ID查询角色信息
     *
     * @param roleId 角色ID
     * @return 角色信息
     */
    @ApiOperation(value = "根据角色ID查询角色信息")
    @PreAuthorize("hasRole('system:role:selectrolebyid')")
    @GetMapping("/selectRoleById/{roleId}")
    public AjaxResult selectRoleById(@ApiParam(name = "roleId", value = "角色id", required = true) @PathVariable("roleId") Long roleId) {
        AjaxResult ajax = AjaxResult.success();
        ajax.put("role_data", lyRoleService.selectRoleById(roleId));
        return ajax;
    }


    /**
     * 修改角色
     *
     * @param lyRole 角色信息
     * @return 结果
     */
    @ApiOperation(value = "修改角色")
    @Log(title = "角色模块", businessType = "2", description = "修改角色")
    @PreAuthorize("hasRole('system:role:updaterole')")
    @PutMapping("/updateRole")
    public AjaxResult updateRole(@RequestBody LyRole lyRole) {
        if (lyRoleService.updateRole(lyRole) > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色+'" + lyRole.getRoleName() + "'失败！！");
    }


    /**
     * 删除角色
     *
     * @param roleId 角色id
     * @return 结果
     */
    @ApiOperation(value = "删除角色")
    @Log(title = "角色模块", businessType = "3", description = "删除角色")
    @PreAuthorize("hasRole('system:role:deleterolebyid')")
    @DeleteMapping("/deleteRoleById/{roleId}")
    public AjaxResult deleteRoleById(@ApiParam(name = "roleId", value = "角色id", required = true) @PathVariable Long roleId) {
        try {
            if (lyRoleService.deleteRoleById(roleId)) {
                return AjaxResult.success("删除成功");
            } else {
                return AjaxResult.error("删除成功");
            }
        } catch (RoleHaveUserCanNotDelException e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 批量删除角色
     *
     * @param roleIds 角色id(list)
     * @return 结果
     */
    @ApiOperation(value = "批量删除角色")
    @ApiImplicitParam(name = "roleIds", value = "角色id(list)", required = true)
    @Log(title = "角色模块", businessType = "3", description = "批量删除角色")
    @PreAuthorize("hasRole('system:role:deleterolebyids')")
    @DeleteMapping("/deleteRoleByIds")
    public AjaxResult deleteRoleByIds(@RequestBody List<Long> roleIds) {
        if (lyRoleService.removeByIds(roleIds)) {
            return AjaxResult.success("删除成功");
        } else {
            return AjaxResult.error("删除成功");
        }
    }


    /**
     * 导出角色信息(Excel)
     *
     * @param generalEntity 角色筛选条件
     * @return 文件名字
     */
    @ApiOperation(value = "角色信息导出为Excel")
    @Log(title = "角色模块", businessType = "7", description = "导出角色信息(Excel)")
    @PreAuthorize("hasRole('system:role:roleexportexcel')")
    @GetMapping("/roleExportExcel")
    public AjaxResult roleExportExcel(GeneralEntity generalEntity) {
        List<LyRole> lyRoleList = lyRoleService.roleExportExcel(generalEntity);
        Workbook work = ExcelExportUtil.exportExcel(new ExportParams(), LyRole.class, lyRoleList);
        String filename = UUID.randomUUID().toString() + "_" + "角色数据" + ".xlsx";
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(FileDownloadUtils.getAbsoluteFile(filename));
            work.write(out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success("导出成功", filename);
    }


    /**
     * 修改角色状态
     *
     * @param updateRoleStatus 角色最新状态（角色id,角色最新状态）
     * @return 角色状态是否修改成功
     */
    @ApiOperation(value = "修改角色状态")
    @Log(title = "角色模块", businessType = "2", description = "修改角色状态")
    @PreAuthorize("hasRole('system:role:updaterolestatus')")
    @PutMapping("/updateRoleStatus")
    public AjaxResult updateRoleStatus(@RequestBody UpdateRoleStatus updateRoleStatus) {
        if (lyRoleService.updateById(new LyRole(updateRoleStatus.getRoleId(), updateRoleStatus.getRoleStatus()))) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改角色状态失败！！");
    }


    /**
     * 根据角色id分页查询用户
     *
     * @param allocationUserCondition 分配用户搜索条件
     * @return 结果
     */
    @ApiOperation(value = "根据角色id分页查询用户")
    @Log(title = "角色模块", businessType = "0", description = "根据角色id分页查询用户")
    @PreAuthorize("hasRole('system:role:selectroleuser')")
    @GetMapping("/selectRoleUser")
    public AjaxResult selectRoleUser(AllocationUserCondition allocationUserCondition) {
        return AjaxResult.success(lyRoleService.selectRoleUser(allocationUserCondition));
    }

    /**
     * 取消绑定
     *
     * @param lyUserRole 角色id、用户id
     * @return 结果
     */
    @ApiOperation(value = "取消绑定")
    @Log(title = "角色模块", businessType = "9", description = "取消绑定")
    @PreAuthorize("hasRole('system:role:cancelbinding')")
    @PutMapping("/cancelBinding")
    public AjaxResult cancelBinding(@RequestBody LyUserRole lyUserRole) {
        if (lyRoleService.cancelBinding(lyUserRole)) {
            return AjaxResult.success("解除成功");
        }
        return AjaxResult.error("解除失败");
    }

    /**
     * 批量取消绑定
     *
     * @param roleId  角色idWW
     * @param userIds 用户id
     * @return 结果
     */
    @ApiOperation(value = "批量取消绑定")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = true),
            @ApiImplicitParam(name = "userIds", value = "用户id", required = true)
    })
    @Log(title = "角色模块", businessType = "9", description = "批量取消绑定")
    @PreAuthorize("hasRole('system:role:batchcancelbinding')")
    @PutMapping("/batchCancelBinding")
    public AjaxResult batchCancelBinding(Long roleId, Long[] userIds) {
        if (lyRoleService.batchCancelBinding(roleId, userIds)) {
            return AjaxResult.success("解除成功");
        }
        return AjaxResult.error("解除失败");
    }

    /**
     * 绑定用户
     *
     * @param roleId  角色id
     * @param userIds 用户id
     * @return 结果
     */
    @ApiOperation(value = "绑定用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roleId", value = "角色id", required = true),
            @ApiImplicitParam(name = "userIds", value = "用户id", required = true)
    })
    @Log(title = "角色模块", businessType = "8", description = "绑定用户")
    @PreAuthorize("hasRole('system:role:bindinguser')")
    @PostMapping("/bindingUser")
    public AjaxResult bindingUser(Long roleId, Long[] userIds) {
        if (lyRoleService.bindingUser(roleId, userIds)) {
            return AjaxResult.success("绑定成功");
        }
        return AjaxResult.error("绑定失败");
    }


}
